<template>
  <TopNavBar :title="_t18('pledge_order_record')" @rightClick="handleRightClick" type="back" />
  <div class="order-detail-page">
    <div class="order-tabs">
      <div :class="['tab', { active: activeTab === 'current' }]" @click="selectActive('current')">
        {{ _t18('exchange_curentrust') }}
      </div>
      <div :class="['tab', { active: activeTab === 'history' }]" @click="selectActive('history')">
        {{ _t18('exchange_hisentrust2') }}
      </div>
    </div>

    <!-- ✅ 当前持仓 -->
    <div v-if="activeTab === 'current'">
      <div v-if="currentOrders.length === 0" class="empty-box">
        <img class="empty-icon" src="/static/img/W2k_c7838bd9_spH.cd0c5744.png" alt="empty" />
        <div class="empty-text">{{ _t18('25_wushuju') }}</div>
      </div>
      <div v-else>
        <div v-for="(order, idx) in currentOrders" :key="idx" class="order-card current">
          <div class="order-card-header">
           <span class="pair">{{ (order.symbol || '').toUpperCase() }}/USD</span>
           <span
             v-if="order.type === 0"
             class="trade-type buy"
           >{{ _t18('purchase') }}</span>
           <span
             v-else-if="order.type === 1"
             class="trade-type sell"
           >{{ _t18('bb_sell1') }}</span>


            <span v-if="Number(order.status) === 0" class="status">{{ _t18('25_weituozhong') }}</span>
          </div>

          <div class="order-card-body">
			  <div class="row"><span class="label">{{ _t18('order_price') }}</span><span class="value">{{ Number(order.delegatePrice) }} </span></div>
            <div class="row"><span class="label">{{ _t18('commission_time') }}</span><span class="value">{{ formatTo12Hour(order.createTime) }}</span>
</div>
            <div class="row"><span class="label">{{ _t18('total_entrustment') }}</span><span class="value">{{ Number(order.delegateTotal) }} </span></div>
            <div class="row"><span class="label">{{ _t18('delegate_value') }}</span><span class="value">{{ order.delegateValue }} USD</span></div>
            <div class="row"><span class="label">{{ _t18('withdraw_commission') }}</span><span class="value">{{ order.fee }}%</span></div>
          </div>
        </div>
      </div>
    </div>

    <!-- ✅ 历史订单 -->
    <div v-if="activeTab === 'history'">
      <div v-if="historyOrders.length === 0" class="empty-box">
        <img class="empty-icon" src="/static/img/W2k_c7838bd9_spH.cd0c5744.png" alt="empty" />
        <div class="empty-text">{{ _t18('25_wushuju') }}</div>
      </div>
      <div v-else>
        <div v-for="(order, idx) in historyOrders" :key="idx" class="order-card history">
          <div class="order-card-header">
           <span class="pair">{{ (order.symbol || '').toUpperCase() }}/USD</span>
            <span
              v-if="order.type === 0"
              class="trade-type buy"
            >{{ _t18('purchase') }}</span>
            <span
              v-else-if="order.type === 1"
              class="trade-type sell"
            >{{ _t18('bb_sell1') }}</span>


           

            <!-- 状态 -->
            <span v-if="Number(order.status) === 1" class="status">{{ _t18('pledge_completed') }}</span>
            <span v-else-if="Number(order.status) === 3" class="status cancel">{{ _t18('25_yichedan') }}</span>
            
          </div>

          <div class="order-card-body">
            <!-- ✅ 撤单 -->
            <template v-if="Number(order.status) === 3">
              <div class="row">
                <span class="label">{{ _t18('25_chengjiaoshijian') }}</span>
               <span class="value">{{ formatTo12Hour(order.createTime) }}</span>

              </div>
              <div class="row">
                <span class="label">{{ _t18('order_price') }}</span>
                <span class="value">{{ order.delegatePrice }} </span>
              </div>
              <div class="row">
                <span class="label">{{ _t18('delegate_value') }}</span>
                <span class="value">{{ order.delegateValue }} </span>
              </div>
			  <div class="row">
			    <span class="label">{{ _t18('total_entrustment') }}</span>
			    <span class="value">{{ order.delegateTotal }} </span>
			  </div>
              <div class="row">
                <span class="label">{{ _t18('withdraw_commission') }}</span>
                <span class="value">{{ order.fee }}</span>
              </div>
            </template>
          
            <!-- ✅ 已完成 -->
            <template v-else>
              <div class="row">
                <span class="label">{{ _t18('25_chengjiaoshijian') }}</span>
                <span class="value">{{ order.dealTime }}</span>
              </div>
              <div class="row">
                <span class="label">{{ _t18('bb_Average_transaction_price') }}</span>
                <span class="value">{{ order.dealPrice }} </span>
              </div>
              <div class="row">
                <span class="label">{{ _t18('25_chengjiaojiazhi') }}</span>
                <span class="value">{{ order.dealValue }} </span>
              </div>
              <div class="row">
                <span class="label">{{ _t18('25_chengjiaozongliang') }}</span>
                <span class="value">{{ order.dealNum }} </span>
              </div>
              <div class="row">
                <span class="label">{{ _t18('withdraw_commission') }}</span>
                <span class="value">{{ order.fee }}</span>
              </div>
            </template>
         、

           </div>

         
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getOrderListCurrencyApi } from '@/api/trade/index'


// ✅ 转换为 12 小时制 AM/PM 时间
function formatTo12Hour(timeStr) {
  if (!timeStr) return '-'
  const match = timeStr.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{1,2}):(\d{2})(?::(\d{2}))?/)
  if (!match) return timeStr
  const [, y, m, d, h, min, s = '00'] = match
  const hour = parseInt(h, 10)
  const ampm = hour >= 12 ? 'PM' : 'AM'
  const displayHour = hour % 12 === 0 ? 12 : hour % 12
  return `${y}-${m}-${d} ${displayHour}:${min}:${s} ${ampm}`
}


const router = useRouter()
const activeTab = ref('current')
const currentOrders = ref([])
const historyOrders = ref([])

function formatTime(value) {
  if (!value) return '-'
  const date = new Date(value)
  if (isNaN(date.getTime())) return value
  const yyyy = date.getFullYear()
  const MM = String(date.getMonth() + 1).padStart(2, '0')
  const dd = String(date.getDate()).padStart(2, '0')
  const hh = String(date.getHours()).padStart(2, '0')
  const mm = String(date.getMinutes()).padStart(2, '0')
  const ss = String(date.getSeconds()).padStart(2, '0')
  return `${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss}`
}

const pageNum = ref(1)
const pageSize = ref(20)

const getList = async (tab = 'current') => {
  try {
    let params = `isAsc=desc&orderByColumn=updateTime&pageSize=${pageSize.value}&pageNum=${pageNum.value}`
    if (tab === 'current') {
      params += `&status=0` // ✅ 当前委托只拉取 status=0
    }

    const res = await getOrderListCurrencyApi(params)
    console.log('接口返回数据：', res.rows)

    if (res.code === 200 && Array.isArray(res.rows)) {
      const all = res.rows.map(i => ({
        ...i,
        status: Number(i.status ?? i.orderStatus ?? 0),
        symbol: i.symbol || i.coinSymbol || i.Symbol || '',
        baseSymbol: i.baseSymbol || 'USD',
        createTime: formatTime(i.createTime),
        dealTime: formatTime(i.dealTime),
        closeTime: formatTime(i.closeTime)
      }))

      if (tab === 'current') {
        currentOrders.value = all.filter(o => o.status === 0)
      } else {
        // ✅ 历史订单：只要 status !== 0
        historyOrders.value = all.filter(o => o.status !== 0)
      }
    } else {
      console.warn('接口返回为空或格式不正确')
    }
  } catch (err) {
    console.error('❌ 获取订单失败:', err)
  }
}

function selectActive(val) {
  activeTab.value = val
  getList(val)
}

onMounted(() => getList('current'))
</script>


<style scoped>
.order-detail-page {
  background: #f7f8fa;
  min-height: 100vh;
  padding: 24px 0 0 0;
}
.order-tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  border-radius: 999px;
  margin: 0 auto 32px auto;
  width: 90%;
  max-width: 380px;
  height: 52px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 4px;
}
.tab {
  flex: 1;
  text-align: center;
  font-size: 14px;
  font-weight: 600;
  padding: 10px 0;
  border-radius: 999px;
  color: #333;
  cursor: pointer;
  transition: all 0.25s ease;
}
.tab.active {
  background: #000;
  color: #fff;
  font-weight: 700;
}
.order-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  padding: 20px 18px 16px 18px;
  margin: 0 auto 16px auto;
  width: 90%;
  max-width: 380px;
}
.order-card-header {
  display: flex;
  align-items: center;
  justify-content: flex-start; /* ✅ 改为左对齐 */
  margin-bottom: 12px;
  padding-bottom: 6px;
  border-bottom: 1px solid rgba(0,0,0,0.05);
  gap: 8px; /* ✅ 增加间距 */
}

.order-card-header .pair {
  font-size: 16px;
  font-weight: 700;
  color: #111;
  margin-right: 6px;
}
.trade-type {
  font-size: 12px;
  font-weight: 600;
  color: #fff;
  padding: 2px 10px;
  border-radius: 6px;
  margin-left: 6px;
  line-height: 18px;
}
.trade-type.buy {
  background-color: #00c693; /* 绿色买入 */
}
.trade-type.sell {
  background-color: #fa190c; /* 红色卖出 */
}


.order-card-header .status {
  margin-left: auto; /* ✅ 状态保持在最右侧 */
  font-size: 14px;
  font-weight: 700;
  color: #00c693;
}

.order-card-header .pair {
  font-size: 16px;
  font-weight: 700;
  color: #111;
}
.order-card-header .status {
  font-size: 14px;
  font-weight: 700;
  color: #00c693;
}
.order-card-header .status.pending { color: #ffaa00; }
.order-card-header .status.cancel { color: #999; }

.order-card-body {
  display: flex;
  flex-direction: column;
  gap: 6px;
  line-height: 1.6;
}
.row {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}
.label {
  color: #666;
}
.value {
  color: #222;
  font-weight: 600;
}
.value.profit { color: #00c693; font-weight: 700; }
.value.loss { color: #fa190c; font-weight: 700; }
.value.waiting { color: #999; font-weight: 500; }

.detail-btn {
  display: block;
  width: 90%;
  margin: 16px auto 0 auto;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 24px;
  font-size: 14px;
  font-weight: 600;
  padding: 10px 0;
}
.detail-btn:hover { background: #222; }

.empty-box {
  margin: 100px auto 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.empty-icon {
  width: 110px;
  height: 110px;
  margin-bottom: 20px;
}
.empty-text {
  font-size: 14px;
  color: #889;
}
.tag {
  font-size: 11px;
  color: #fff;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 8px 24px 8px 8px;
  height: 17px;
  line-height: 17px;
  margin-right: 10px;
  display: flex;
  align-items: center;
  gap: 2px;
}
.tag.up { background: #fa190c; }
.tag.down { background: #00c693; }
.arrow { font-size: 13px; font-weight: 700; }
</style>
